package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.user.dto.FollowBehaviorDto;
import com.heima.user.dto.LoginDto;
import com.heima.user.dto.UserRelationDto;
import com.heima.user.entity.ApAuthor;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserFollow;
import com.heima.user.feign.ArticleFegin;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserFollowService;
import com.heima.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-20
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {
//用户appd登录
    @Override
    public ResponseResult login(LoginDto dto) {
//       正常用户登录的话少一个都不行
        if(dto==null||(dto.getEquipmentId()==null&&dto.getPassword()==null&&dto.getPhone()==null)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

        }
//        如果参数都有开始查询  根据手机号和密码查询
        if(dto.getPhone()!=null&&dto.getPassword()!=null){
            LambdaQueryWrapper<ApUser> query=new LambdaQueryWrapper<>();
            query.eq(ApUser::getPhone,dto.getPhone());
            ApUser one = this.getOne(query);
           if(one==null){
               return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);

           }
           String pw=dto.getPassword()+one.getSalt();


            String s = DigestUtils.md5DigestAsHex(pw.getBytes());
            if(s.equals(one.getPassword())){
                Map<String,Object> objectHashMap=new HashMap<>();
                objectHashMap.put("userId",one.getId());
                String token = AppJwtUtil.getToken(objectHashMap);
                Map<String,Object>map=new HashMap<>();
                map.put("token",token);
                return ResponseResult.okResult(map);


            }
        }
        if(dto.getEquipmentId()!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("userId",0);
            String token = AppJwtUtil.getToken(map);
            Map<String,Object>stringObjectMap=new HashMap<>();
            stringObjectMap.put("token",token);
            return ResponseResult.okResult(token);
        }


        return null;
    }
//    关注和取消功能

    @Autowired
    private ArticleFegin articleFegin;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Value("${topic.followBehaviorTopic}")
    private String FollowBehaviorTopic;

    @Autowired
    private IApUserFollowService followService;
    @Override
    public ResponseResult follow(UserRelationDto dto) {
//        先校验登录没有登录
        User user = AppThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


//        然后构建apUserFllow
        ApUserFollow apUserFollow=new ApUserFollow();
        apUserFollow.setUserId(user.getUserId());
        ApUser apUser = this.getById(user.getUserId());
        apUserFollow.setUserName(apUser.getName());

//        根据文章id远程调用查询作者id
        ResponseResult<ApAuthor> author = articleFegin.getAuthorById(dto.getAuthorId());
        if(author.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            if(author!=null){
                ApAuthor apAuthor = author.getData();
                apUserFollow.setFollowId(apAuthor.getId());
                apUserFollow.setFollowName(apAuthor.getName());
            }
        }
        apUserFollow.setLevel(1);
        apUserFollow.setCreatedTime(new Date());
//        判断该用户是否银镜关注了词作者
//        根据 用户id  和作者id
        LambdaQueryWrapper<ApUserFollow> query=new LambdaQueryWrapper<>();
        query.eq(ApUserFollow::getUserId,apUserFollow.getUserId());
        query.eq(ApUserFollow::getFollowId,apUserFollow.getFollowId());
        ApUserFollow one = followService.getOne(query);
//        再继续判断 是否存在 布直接加  直接 删除
        if (one==null){
            if (dto.getOperation()==0){
                followService.save(apUserFollow);
            }
        }else {
            if(dto.getOperation()==1){
                followService.remove(query);
            }
        }
        FollowBehaviorDto followBehaviorDto=new FollowBehaviorDto();
        followBehaviorDto.setUserId(user.getUserId());
        followBehaviorDto.setFollowId(apUserFollow.getFollowId());
        followBehaviorDto.setOperation(dto.getOperation());
        followBehaviorDto.setEquipmentId(dto.getEquipmentId());
        String json = JSON.toJSONString(followBehaviorDto);
        kafkaTemplate.send(FollowBehaviorTopic, json);


            return ResponseResult.okResult();
    }
}
